package xyz.thoughtset.viewer.modules.api.entity;

import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import xyz.thoughtset.viewer.common.core.entity.BaseMeta;
import xyz.thoughtset.viewer.common.crud.core.annotation.ApiCRUDPower;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import xyz.thoughtset.viewer.modules.datarel.entity.DataRel;

import java.util.List;
import java.util.Map;

@TableName
@Data
@AllArgsConstructor
@ApiCRUDPower(insert = false,save = true,update = false,list = true)
public class ApiInfo extends BaseMeta {
//    private String funId;
    @TableField(whereStrategy = FieldStrategy.NOT_EMPTY)
    private String url;
    private Integer queryType;
    private Integer cacheTime;

    @TableField(exist = false)
    private List<ApiParam> apiParams;
    @TableField(exist = false)
    private List<DataRel> dataRels;

    @TableField(exist = false)
    private transient Map<String,List<DataRel>> dataRelMaps;

    public ApiInfo() {
        this.queryType = null;
        this.statesCode = null;
    }

    public ApiInfo(String id, Integer statesCode) {
        this.id = id;
        this.statesCode = statesCode;
    }

    public Map<Integer,List<ApiParam>> groupParams(){
        if (ObjectUtils.isEmpty(apiParams)) {
            return Map.of();
        }
        return apiParams.parallelStream()
                .collect(java.util.stream.Collectors.groupingBy(ApiParam::getParamType));
    }

    public Map<String,List<DataRel>> groupRels(){
        if (!ObjectUtils.isEmpty(dataRelMaps)) {
            return dataRelMaps;
        }
        if (ObjectUtils.isEmpty(dataRels)) {
            return Map.of();
        }
        dataRelMaps = dataRels.stream()
                .collect(java.util.stream.Collectors.groupingBy(DataRel::getTopic));
        return dataRelMaps;
    }


    public RequestMethod apiReqMethod() {
        return queryType==11?RequestMethod.GET:RequestMethod.POST;
    }

}
